// pages/category/category.js

const util = require('../../utils/util');
const {GoodsCount, CatalogList, CatalogCurrent } = require('../../config/api');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    catalogList: [],
    catalogCurrent: [],
    subCatalogCurrent: [],
    goodsCount:0,
    activeKey:0,
    // catalogIdList:[],//侧边栏每项的id
    // subCatalogCurrentNameAndPic:[],//每个子页面的名称与顶部图片
    subPageName:'居家',
    subPagePic:'http://yanxuan.nosdn.127.net/e8bf0cf08cf7eda21606ab191762e35c.png',
  },
  // 获取全部分类数据
  getCatalogData() {
    let that = this;
    util.request(CatalogList).then(res => {
      let { categoryList, currentCategory, currentSubCategory } = res.data
      if (res.errno == 0) {
        // // 把侧边标签的每一项的id放入新数组
        // categoryList.forEach(item=>{
        //   this.data.catalogIdList.push(item.id)
        // })
        that.setData({
          catalogList: categoryList,
          catalogCurrent: currentCategory,
          subCatalogCurrent: currentSubCategory,
          
        })
      }
    });
    // 获取假搜索栏的商品数量
    util.request(GoodsCount).then(res=>{
      if(res.errno==0){
        that.setData({
          goodsCount:res.data.goodsCount
        })
      }
    })
  },

  // 获取当前分类的数据
  getCurrentSubCateData(id){
    let that = this;
    util.request(CatalogCurrent+'/?id='+id).then(res=>{
      let {  currentCategory, currentSubCategory } = res.data
      if(res.errno==0){
        
        that.setData({
          catalogCurrent: currentCategory,
          subCatalogCurrent:currentSubCategory,
        })
      }
    })
  },

  // 侧边栏事件
  onChange(e){
    // console.log(e.detail);
    let that = this;
    this.setData({
      activeKey:e.detail,
      subPageName:this.data.catalogList[e.detail].name,
      subPagePic:this.data.catalogList[e.detail].picUrl
    })
    
    let id = this.data.catalogList[e.detail].id;
    this.getCurrentSubCateData(id)
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getCatalogData()
  },

  onPullDownRefresh(){
    // let id = this.data.catalogList[this.data.activeKey].id;
    // console.log(id);
    
    this.setData({
      activeKey:0,
      subPageName:this.data.catalogList[0].name,
      subPagePic:this.data.catalogList[0].picUrl
    })
    let id = this.data.catalogList[0].id
    wx.showNavigationBarLoading();//在标题栏中显示加载
    this.getCatalogData();
    this.getCurrentSubCateData(id);
    wx.hideNavigationBarLoading();//完成停止加载
    wx.stopPullDownRefresh();//停止下拉刷新
  }

})